package com.zhoufeng.udp.service;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggerFactory;

import com.jfinal.plugin.activerecord.Record;
import com.zhoufeng.common.Common;
import com.zhoufeng.controller.IndexController;
import com.zhoufeng.db.DbMng;
import com.zhoufeng.model.DeviceConfigure;
import com.zhoufeng.model.DeviceModel;
import com.zhoufeng.model.Recievedata;
import com.zjhbkj.xinfen.db.DBMgr;
import com.zjhbkj.xinfen.model.SendComsModel;
import com.zjhbkj.xinfen.util.CommandUtil;

import de.greenrobot.event.EventBus;

public class UDPProcessThread implements Runnable {
	
	private static final Logger logger = Logger.getLogger(UDPProcessThread.class);
	
	private DatagramPacket  localDatagramPacket = null;
	private DatagramSocket mReceiveSocket = null;
	private DatagramSocket mSendSocket;
	private Record modelappmsg;
	
	private byte[] msg;
	
	public UDPProcessThread(DatagramPacket  gdatagramPacket, Record modelappmsg) {
		byte[] arrayOfByte = new byte[Common.COMMAND_LENGTH];
		this.msg = arrayOfByte;
		this.localDatagramPacket = gdatagramPacket;
		this.modelappmsg = modelappmsg;
		try {
			this.mReceiveSocket = new DatagramSocket();
		} catch (SocketException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
	}
	
	
	public void closeConnection() {
		if (this.mReceiveSocket != null) {
			this.mReceiveSocket.close();
			this.mReceiveSocket = null;
		}
		if (this.mSendSocket == null)
			return;
		this.mSendSocket.close();
		this.mSendSocket = null;
	}
	
	@Override
	public void run() {
		
		byte[] arrayOfByte2 = localDatagramPacket.getData();
		System.out.println(arrayOfByte2.length);
		String ss = complieData(arrayOfByte2);
		if (ss != null && ss.length() > 65)
			ss = ss.substring(0, 65).trim();
		// boolean bool =
		// localRcvComsModel.receiveCommand(arrayOfByte2);
		if (ss != null && ss.length() == 65) {
			String[] ssarr = ss.split(" ");

			if ("40".equals(ssarr[0]) && "DA".equals(ssarr[1])) {
				try {
					saveDeviceDataAndSendDeviceConfig(localDatagramPacket, ss);
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("保存设备发来信息|发送配置信息-出现错误：" + e.getMessage() + ",recieve data:" + ss);
				}
			} else if ("AA".equals(ssarr[0]) && "EA".equals(ssarr[1])) {
				try {
					saveDeviceConfigAndSendDeviceDataToAPP(localDatagramPacket, ss, modelappmsg);
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("保存APP发来配置信息|发送配置信息-出现错误：" + e.getMessage() + ",recieve data:" + ss);
				}
			}else if("40".equals(ssarr[0]) && "9A".equals(ssarr[1])){
				try {
					saveDeviceFilterData(localDatagramPacket, ss);
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("保存滤网信息|发送滤网设置信息-出现错误：" + e.getMessage() + ",recieve data:" + ss);
				}
			}else if("AA".equals(ssarr[0]) && "8A".equals(ssarr[1])){
				try {
					saveDeviceFilterSetter(localDatagramPacket, ss);
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("保存滤网信息|发送滤网设置信息-出现错误：" + e.getMessage() + ",recieve data:" + ss);
				}
			}

		} else {
			String send = "数据错误，保存失败！";
			byte[] bsend = send.getBytes();
			InetAddress addr = localDatagramPacket.getAddress();
			int port = localDatagramPacket.getPort();
			DatagramPacket sendPacket = new DatagramPacket(bsend, bsend.length, addr, port);
			try {
				this.mReceiveSocket.send(sendPacket);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		closeConnection();
		
	}
	
	
	
	private void saveDeviceFilterSetter(DatagramPacket localDatagramPacket2, String ss) {
		DbMng.saveDeviceFilterSetter(ss);
	}


	private synchronized void saveDeviceFilterData(DatagramPacket localDatagramPacket, String ss) {
		DbMng.saveDeviceFilterData(ss);
	}

	/**
	 * 
	 * 接收APP配置信息并发送设备数据信息到APP
	 * 
	 * @param localDatagramPacket
	 * @param ss
	 * @param modelappmsg2 
	 * @throws IOException
	 */
	private synchronized void saveDeviceConfigAndSendDeviceDataToAPP(DatagramPacket localDatagramPacket, String ss, Record modelappmsg2){
		DbMng.saveDeviceConfig(ss,modelappmsg2);
	}

	/**
	 * 
	 * 接收设备数据信息和发送配置到设别
	 * 
	 * @param localDatagramPacket
	 * @param ss
	 * @throws IOException
	 */
	private synchronized void saveDeviceDataAndSendDeviceConfig(DatagramPacket localDatagramPacket, String ss) {
		DbMng.saveinfo(ss);
	}

	private String complieData(byte[] data) {

		String retstr = null;
		retstr = new String(data);
		if (data.length < 65) {
			retstr = CommandUtil.bytesToHexString(data);
		}
		return retstr;
	}

	public void send(DatagramPacket paramDatagramPacket) {
		SendComsModel localSendComsModel = (SendComsModel) DBMgr.getHistoryData(SendComsModel.class, "EA");
		if (localSendComsModel == null)
			return;
		byte[] arrayOfByte = CommandUtil.getCommand(localSendComsModel.toString());
		int i = arrayOfByte.length;
		InetAddress localInetAddress1 = paramDatagramPacket.getAddress();
		int j = paramDatagramPacket.getPort();
		DatagramPacket localDatagramPacket = new DatagramPacket(arrayOfByte, i, localInetAddress1, j);
		try {
			this.mSendSocket.send(localDatagramPacket);
			EventBus localEventBus1 = EventBus.getDefault();
			StringBuilder localStringBuilder1 = new StringBuilder("消息发送成功");
			InetAddress localInetAddress2 = paramDatagramPacket.getAddress();
			StringBuilder localStringBuilder2 = localStringBuilder1.append(localInetAddress2).append(":");
			int k = paramDatagramPacket.getPort();
			String str1 = new Integer(k).toString();
			localEventBus1.post(str1);
			return;
		} catch (IOException localIOException) {
			localIOException.printStackTrace();
			EventBus localEventBus2 = EventBus.getDefault();
			StringBuilder localStringBuilder3 = new StringBuilder("消息发送失败.");
			String str2 = localIOException.toString();
			String str3 = str2;
			localEventBus2.post(str3);
		}
	}
	

}
